﻿/***************************************
= (document.ready)
-------------------------------------- */
$(function () {
    // Show menu when a list item is clicked
    highlights();

    // Popup Quiz
    $("#popup-quiz-close").click(function () {
        disablePopupQuiz();
    });

    $("#bg-popup-quiz").click(function () {
        disablePopupQuiz();
    });
});

function abc() {
    $('body').click(function () {        
        disablePopupQuiz();
    });
}

//**************************************************************************************************************************************************************//
// COMMON
//**************************************************************************************************************************************************************//

var popupStatus = 0;

function showPopupQuiz() {
    if (popupStatus == 0) {
        $('#bg-popup-quiz').css({ 'opacity': '0.6' });
        $('#bg-popup-quiz').fadeIn('slow');
        $('#popup-quiz').fadeIn('slow');
        popupStatus = 1;

        var wWidth = document.documentElement.clientWidth;
        var wHeight = document.documentElement.clientHeight;

        var popupWidth = $('#popup-quiz').width();
        var popupHeight = $('#popup-quiz').height();

        $('#popup-quiz').css({ 'position': 'fixed', 'top': wHeight / 2 - popupHeight / 2, 'left': wWidth / 2 - popupWidth / 2 });

        $('#bg-popup-quiz').css({ 'height': wHeight }); // only need force for IE6
    }
}

function disablePopupQuiz() {
    $('#bg-popup-quiz').fadeOut('slow');
    $('#popup-quiz').fadeOut('slow');
    popupStatus = 0;
}

// Press Escape Event!
$(document).keypress(function (e) {
    if (e.keyCode == 27 && popupStatus == 1) {
        disablePopupQuiz();
    }
    if (e.keyCode == 27) {
        closePreview();
    }
});


/***************************************
= String Format
-------------------------------------- */
//#region
String.format = function (text) {
    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there's nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
                                                arguments[token + 1]);
    }
    return text;
};
//#endregion

function LoadImage(obj, url) {
    obj.src = url;
    obj.onerror = null;
}

/***************************************
= Tiny MCE
-------------------------------------- */
function getMCE() {
    var content = tinyMCE.get('elm1').getContent();
    //console.log('getMCE: ' + content);    
    if (content.length > 0)
        $('#txtBody').val(content);
}

function setMCE(content) {
    console.log('setMCE: ' + content);
    tinyMCE.execCommand('mceInsertContent', false, content);
    //tinyMCE.execCommand('mceInsertContent', false, img);
}

/***************************************
= File Manager Functions
-------------------------------------- */
function openFileManager(type) {    
    var adminUserId = Base64.decode(AdminUserId);
    if (adminUserId > 0) {
        var urlFolder = String.format("files/{0}/{1}", adminUserId, (new Date().getFullYear()));
        viewDirectories(type, urlFolder, true);
        showPopupQuiz();
    }                    
}

/***************************************
= IZ File Manager Functions
-------------------------------------- */
//#region
function openIZFileManager(type) {
    var w = window.open('/Controls/IZFileManager.aspx?type=' + type, 'File Manager', 'status = 1, height = 470, width = 810');
    w.focus();
    return false;
}
//#endregion

//#region  
// Callback Function Of IZFileManager
function setTargetField(value, type) {
  
    switch (type) {
        case "article":
            $("#txtImage").val(value);
            break;
        case "zodiac":
            $("#txtImageDescription").val(value);
            break;
        case "data":
            $("#txtFilePath").val(value);
            break;
        case "smallsize":
            // set list src image to textbox
            $('#txtImageList').val(value);

            var smallSizeItem = '';
            var splitSmallSize = value.split("►");
            $(splitSmallSize).each(function (index, val) {
                if (val.toString().length > 0) {
                    smallSizeItem += createSmallSize("", val.toString(), "");
                }
            });

            $('.smallsize').append(smallSizeItem);
            $('.topDir').tipsy({ fade: true, gravity: 's' });
            removeSmallSize();
            break;
        case "hehehoro":
            // set list src image to textbox
            $('#txtImageList').val(value);

            var hehehoroItem = '';
            var splitHehehoro = value.split("►");
            $(splitHehehoro).each(function (index, val) {
                if (val.toString().length > 0) {
                    hehehoroItem += createHehehoro(val.toString());
                }
            });

            $('.hehehoro-album').append(hehehoroItem);
            $('.topDir').tipsy({ fade: true, gravity: 's' });
            removeHehehoro();
            break;             
    }
    window.focus();
}
//#endregion

//**************************************************************************************************************************************************************//

/***************************************
= Get All Rows Have Checked
-------------------------------------- */
//#region 
function selectAllRows(spanChk) {    
    var oItem = spanChk.children;
    var theBox = (spanChk.type == "checkbox") ?
            spanChk : spanChk.children.item[0];
    xState = theBox.checked;
    //elm = theBox.form.elements;
    elm = $("#grdList :checkbox");

    for (i = 0; i < elm.length; i++)
        if (elm[i].type == "checkbox" &&
                  elm[i].id != theBox.id) {
            if (elm[i].checked == xState)
                elm[i].click();
        }
}
//#endregion

/***************************************
= Active Tab
-------------------------------------- */
//#region
function activeTab(tabName) {    
    switch (tabName) {
        case "IsPublished":
            $("#tab8").addClass('activeTab');        
            break;
        case "IsWaitingForPublish":
            $("#tab2").addClass('activeTab');
            break;
        case "IsDraft":
            $("#tab1").addClass('activeTab');
            break;
        case "IsReturned":
            $("#tab4").addClass('activeTab');
            break;
        case "IsRemoved":
            $("#tab16").addClass('activeTab');
            break;
        case "SmallSize":
            $("#tab8").addClass('activeTab');
            break;
        case "BigSize":
            $("#tab9").addClass('activeTab');
            break;
        case "HeheHoro":
            $("#tab6").addClass('activeTab');
            break;
        case "Library":
            $("#tab13").addClass('activeTab');
            break;
        case "HoroDaily":
            $("#tab1").addClass('activeTab');
            break;
        case "CoupleSeat":
            $("#tab3").addClass('activeTab');
            break;
        case "SingleSeat":
            $("#tab4").addClass('activeTab');
            break;
        case "Round1":
            $("#tab11").addClass('activeTab');
            break;
        case "Round2":
            $("#tab22").addClass('activeTab');
            break;
        case "Round3":
            $("#tab33").addClass('activeTab');
            break;             
    }
}
//#endregion

/***************************************
= Active Left Navigator
-------------------------------------- */
//#region    
function activeLeftNav(menuId) {    
    if (typeof(menuId) == 'undefined') {
        return;
    }

    if (menuId == 21) {
        $('.pacman').find('a:first').addClass('active'); // Fix menu Hehe Horo
    }

    if (menuId == 5) {
        $('.pacman').find('a:first').addClass('active'); // Fix menu Hehe Horo
    }

    if (menuId == 37) {
        $('.airplane').find('a:first').addClass('active'); // Fix menu Vip Quiz
    }

    if (menuId == 39) {
        $('.star').find('a:first').addClass('active'); // Fix menu Top Quizzer
    }
    
    if (menuId == 41) {
        $('.userComment').find('a:first').addClass('active'); // Fix menu Top Quizzer
    }
    
    var li = $('ul.sub li a.sm' + menuId).parents('li');
    //console.log(li);
    
    var a = $(li).find('a:first');

    $(a).addClass('active');
    
    $('.active').collapsible({
        defaultOpen: 'current',
        cookieName: 'nav',
        speed: 300
    });

    $('.exp').collapsible({
        defaultOpen: 'current',
        cookieName: 'navAct',
        cssOpen: 'active',
        cssClose: 'inactive',
        speed: 300
    });
    
    var sub = $(li).find('.sub:first');
    $(sub).removeAttr('style').show();
}
//#endregion

// Delegare Tooltip
//#region
function delegateTooltip() {
    $('.topDir').tipsy({ fade: true, gravity: 's' });
}
//#endregion

//**************************************************************************************************************************************************************//
// HEHEHORO
//**************************************************************************************************************************************************************//

/***************************************
= Create Hehehoro
-------------------------------------- */
//#region
function createHehehoro(imagePath) {
    var html = '';
    html += '<div class="hehehoro-item">';
    html += '<div class="mt10">';
    html += '<a class="btn14 mr17 floatright topDir" onclick="removeHehehoro(this);" title="Xóa ảnh"><img src="/images/icons/dark/close.png" alt="" /></a>';
    html += '</div>';
    html += '<div class="fix"></div>';

    html += '<div class="rowElem nobg">';
    html += '<label>Chọn ảnh</label>';
    html += '<div class="formRight">';
    html += String.format('<input id="sImg_{1}" type="text" style="width: 500px" class="validate[required] sImage floatleft" value="{0}" />', imagePath, removeSign(imagePath));
    html += String.format('<a class="floatleft btn14 mr5 ml5 topDir" title="Chọn file ảnh" onclick="openFileManager(\'sImg_{0}\', \'textbox\');" href="#"><img src="/images/icons/dark/folder.png" alt="" /></a>', removeSign(imagePath));
    //html += '<a class="btn14 floatleft ml5 topDir" title="Di chuột vào textbox để xem ảnh."><img alt="" src="/images/icons/dark/arrowLeft.png"></a>';
    //html += '<span style="line-height: 28px;">&nbsp;(125 x 113)</span>';
    html += String.format('<a class="floatleft btn14 topDir" title="Xem ảnh" onmousemove="viewImage(\'sImg_{0}\', \'detail\', 0, 0);">', removeSign(imagePath));
    html += '<img src="/images/icons/dark/image2.png" alt="" /></a>';
    html += '<span style="line-height: 28px;">&nbsp;(700 x Auto)</span>';  
    html += '</div>';
    html += '<div class="fix"></div>';
    html += '</div>';

    html += '<div class="curves"></div>';
    html += '</div>';

    return html;
}
//#endregion

/***************************************
= Remove Hehehoro
-------------------------------------- */
//#region
function removeHehehoro(obj) {
    $(obj).parents('.hehehoro-item').fadeOut('slow', function () {
        $(this).remove();
    });
}
//#endregion

/***************************************
= Get Data Hehehoro
-------------------------------------- */
//#region
function getDataHehehoro() {
    var imageList = '';
    $('.hehehoro-item').each(function () {
        imageList += $(this).find('.sImage').val() + '►';
    });
    // set list image to textbox
    $('#txtImageList').val(imageList);
}
//#endregion

/***************************************
= Bind Data Hehehoro
-------------------------------------- */
//#region
function binDataHehehoro(hehehoroId) {
    var lstHehehoro = '';
    $.getJSON("/Handlers/EventHandler.ashx", { 'command': 'bindhehehorodetailsbyhehehoro', 'id': hehehoroId }, function (result) {
        for (var i = 0; i < result.length; i++) {
            lstHehehoro += createHehehoro(result[i].Image);
        }
        $('.hehehoro-album').html(lstHehehoro);
    });
}
//#endregion

//**************************************************************************************************************************************************************//
// SMALL SIZE
//**************************************************************************************************************************************************************//

/***************************************
= Create Small Size
-------------------------------------- */
//#region
function createSmallSize(title, imagePath, result) {            
    var html = '';
    html += '<div class="smallsize-item">';
    html += '<div class="mt10">';
    html += '<a class="btn14 mr17 floatright topDir" onclick="removeSmallSize(this);" title="Xóa đáp án"><img src="/images/icons/dark/close.png" alt="" /></a>';
    html += '</div>';
    html += '<div class="fix"></div>';

    html += '<div class="rowElem nobg">';
    html += '<label>Tiêu đề</label>';
    html += '<div class="formRight"><input type="text" class="validate[required] sTitle" value="' + title + '"/></div>';
    html += '<div class="fix"></div>';
    html += '</div>';

    html += '<div class="rowElem">';
    html += '<label>Chọn ảnh</label>';
    html += '<div class="formRight">';
    html += String.format('<input id="sImg_{1}" type="text" style="width: 500px" class="validate[required] sImage floatleft" onmousemove="quickViewImage(\'{0}\', 200, 181);" onmouseout="closePreview();" value="{0}" />', imagePath, removeSign(imagePath));    
    html += String.format('<a class="floatleft btn14 mr5 ml5 topDir" title="Chọn file ảnh" onclick="openFileManager(\'sImg_{0}\', \'textbox\');" href="#"><img src="/images/icons/dark/folder.png" alt="" /></a>', removeSign(imagePath));
    html += '<a class="btn14 floatleft ml5 topDir" title="Di chuột vào textbox để xem ảnh."><img alt="" src="/images/icons/dark/arrowLeft.png"></a>';
    html += '<span style="line-height: 28px;">&nbsp;(125 x 113)</span>';
    html += '</div>';
    html += '<div class="fix"></div>';
    html += '</div>';            

    html += '<div class="rowElem">';
    html += '<label>Lời chiêm tinh</label>';
    html += '<div class="formRight"><textarea name="textarea" class="validate[required] sResult" cols="" rows="5">' + result + '</textarea></div>';
    html += '<div class="fix"></div>';
    html += '</div>';
    html += '<div class="curves"></div>';
    html += '</div>';    

    return html;    
}
//#endregion

/***************************************
= Remove Small Size
-------------------------------------- */
//#region
function removeSmallSize(obj) {   
    $(obj).parents('.smallsize-item').fadeOut('slow', function () {
        $(this).remove();
    });                            
}
//#endregion

/***************************************
= Get Data Small Size
-------------------------------------- */
//#region
function getDataSmallSize() {
    var imageList = '';
    $('.smallsize-item').each(function () {
        imageList += $(this).find('.sImage').val() + '►';
    });
    // set list image to textbox
    $('#txtImageList').val(imageList);
    
    var contentList = '';
    $('.smallsize-item').each(function () {
        contentList += $(this).find('.sTitle').val() + '♥' + $(this).find('.sResult').val() + '►';
    });
    // set list title, result to textbox
    $('#txtContentList').val(contentList);
}
//#endregion

/***************************************
= Bind Data Small Size
-------------------------------------- */
//#region
function binDataSmallSize(quizzyShopId) {
    var lstSmallSize = '';
    $.getJSON("/Handlers/EventHandler.ashx", { 'command': 'bindsmallsizebyquizzyshop', 'id': quizzyShopId }, function (result) {
        for (var i = 0; i < result.length; i++) {
            lstSmallSize += createSmallSize(result[i].Title, result[i].Image, result[i].Result);
        }
        $('.smallsize').html(lstSmallSize);
    });
}
//#endregion
//**************************************************************************************************************************************************************//
// HighLights (Right Context Menu)
//**************************************************************************************************************************************************************//

//#region
function highlights() {
    $("#grdList tr td").contextMenu({
        menu: 'myMenu'
    }, function (action, el, pos) {
        console.log('Action: ' + action + " - Id: " + $(el).parents('tr:first').attr("id"));
        var container = $(el).parents('tr:first');

        switch (action) {
            case "homepage":
                container.find('td:eq(2) img').attr({ 'src': '/images/icons/color/pin.png', 'title': 'Nổi bật trang chủ' }).addClass('btn14');
                break;
            case "category":
                container.find('td:eq(2) img').attr({ 'src': '/images/icons/color/paper-clip.png', 'title': 'Nổi bật mục' }).addClass('btn14');
                break;
            case "remove":
                container.find('td:eq(2) img').attr({ 'src': '', 'title': '' }).removeClass('btn14');
                break;
            case "blacklist":
                container.find('td:eq(5) img').attr({ 'src': '/images/icons/color/minus-circle.png', 'title': 'Black list' }).addClass('btn14');
                break;
            case "highlight":
                container.find('td:eq(5) img').attr({ 'src': '/images/icons/color/trophy.png', 'title': 'Nổi bật' }).addClass('btn14');
                break;                
            case "remove-ming":
                container.find('td:eq(5) img').attr({ 'src': '', 'title': '' }).removeClass('btn14');
                break;
        }

        // Người dùng Ming
        if (action == 'blacklist' || action == 'highlight' || action == 'remove-ming') {
            var splitValue = container.attr("id").split('-');
            if (parseInt(splitValue[0]) > 0) {
                $.post('/Handlers/EventHandler.ashx', { 'command': 'mingsettypeid', 'id': splitValue[0], 'action': action }, function () {
                    switch (action) {
                        case "blacklist":
                            $.jGrowl('Thiết lập người chơi black list thành công', { header: 'Thông báo' });
                            break;
                        case "highlight":
                            $.jGrowl('Thiết lập người chơi nổi bật thành công', { header: 'Thông báo' });
                            break;
                        case "remove-ming":
                            $.jGrowl('Xóa thiết lập thành công', { header: 'Thông báo' });
                            break;
                    }
                });
            }  
        }
        else {
            // Thiết lập nổi bật trang chủ, nổi bật chuyên mục và xóa thiết lập cho bài viết
            var splitValue = container.attr("id").split('-');
            if (parseInt(splitValue[0]) > 0 && parseInt(splitValue[1]) > 0 && splitValue[1].length > 0) {

                $.post('/Handlers/EventHandler.ashx', { 'command': 'highlighthomepagecategory', 'adminUserId': splitValue[0], 'action': action, 'id': splitValue[1], 'table': splitValue[2] }, function () {
                    switch (action) {
                        case "homepage":
                            $.jGrowl('Thiết lập nổi bật trang chủ thành công', { header: 'Thông báo' });
                            break;
                        case "category":
                            $.jGrowl('Thiết lập nổi bật chuyên mục thành công', { header: 'Thông báo' });
                            break;
                        case "remove":
                            $.jGrowl('Xóa thiết lập thành công', { header: 'Thông báo' });
                            break;
                    }
                });
            }    
        }
        
        $('.topDir').tipsy({ fade: true, gravity: 's' });
    });
}

//#endregion

//**************************************************************************************************************************************************************//
// BIG SIZE
//**************************************************************************************************************************************************************//

/***************************************
= Show Big Size Result
-------------------------------------- */
//#region
function showBigSizeResult() {
    var max = 0;
    $('.bigsize-item .answerList').each(function () {
        var count = $(this).find('.rowElem').length;
        if (count > max)
            max = count;
    });

    if (max > 0) {        
        var bigSizeResult = '';
        bigSizeResult += '<div class="rowElem">';
        bigSizeResult += '<label>Lời chiêm tinh</label>';
        bigSizeResult += '<div class="formRight">';            
        bigSizeResult += '<textarea name="textarea" class="bResult" cols="" rows="4" style="width: 630px"></textarea>';
        bigSizeResult += '<div class="floatright"><a onclick="removeBigSizeResult(this);" title="Xóa đáp án" class="btn14 mb5 topDir"><img alt="" src="/images/icons/dark/close.png"></a></div>';            
        bigSizeResult += '</div>';
        bigSizeResult += '<div class="fix"></div>';
        bigSizeResult += '</div>';

        var currentCount = $('.bigsize-result .rowElem').length;

        var html = '';
        for (var i = 0; i < max - currentCount; i++) {
            html += bigSizeResult;
        }
        
        $('.bigsize-result').append(html);
        $('#bigSize-result-container').show();
    }
}
//#endregion

/***************************************
= Remove Big Size Result
-------------------------------------- */
//#region
function removeBigSizeResult(obj) {
    $(obj).parents('.rowElem:first').fadeOut('slow', function () {
        $(this).remove();
    });
}
//#endregion

/***************************************
= Get Data Big Size
-------------------------------------- */
//#region
function getDataBigSize() {
    // set list big size result to textbox
    var bigSizeResult = '';
    $('.bigsize-result .bResult').each(function () {
        bigSizeResult += $(this).val() +'►';
    });
    if (bigSizeResult.length > 0) {
        $('#txtBigSizeResultList').val(bigSizeResult);
    }
        
    var questionList = '';
    $('.bigsize-item').each(function() {
        questionList += $(this).find('.bQuestion').val() + '►';
    });
    // set list question to textbox
    $('#txtQuestionList').val(questionList);

    var answerList = '';
    $('.bigsize-item').each(function () {
        $(this).find('.rowElem').each(function () {
            if ($(this).find('.bAnswer').val() != undefined) 
                answerList += $(this).find('.bAnswer').val() + '♥';            
        });
        answerList += '►';
    });
    // set list answer to textbox
    $('#txtAnswerList').val(answerList);
}
//#endregion

/***************************************
= Bind Data Big Size
-------------------------------------- */
//#region
function binDataBigSize(quizzyShopId) {
    // question & answer
    var lstBigSize = '';
    $.getJSON("/Handlers/EventHandler.ashx", { 'command': 'bindbigsizebyquizzyshop', 'id': quizzyShopId }, function (result) {
        for (var i = 0; i < result.length; i++) {
            lstBigSize += '<div class="bigsize-item">';
            lstBigSize += bindQuestionAnswer(result[i].ListQuestion[0].Question, result[i].ListAnswer);
            lstBigSize += '</div>';
        }

        $('.bigsize').html(lstBigSize);
    });

    // big size result
    $.getJSON("/Handlers/EventHandler.ashx", { 'command': 'bindbisizeresult', 'id': quizzyShopId }, function (result) {
        var bigSizeResult = '';
        
        for (var i = 0; i < result.length; i++) {            
            bigSizeResult += '<div class="rowElem">';
            bigSizeResult += '<label>Lời chiêm tinh</label>';
            bigSizeResult += '<div class="formRight">';
            bigSizeResult += '<textarea name="textarea" class="auto bResult" cols="" rows="4" style="width: 630px">' + result[i].Result + '</textarea>';
            bigSizeResult += '<div class="floatright"><a onclick="removeBigSizeResult(this);" title="Xóa đáp án" class="btn14 mb5 topDir"><img alt="" src="/images/icons/dark/close.png"></a></div>';
            bigSizeResult += '</div>';            
            bigSizeResult += '<div class="fix"></div>';
            bigSizeResult += '</div>';
        }

        $('.bigsize-result').html(bigSizeResult);
        $('#bigSize-result-container').show();
    });
}

function bindQuestionAnswer(question, listAnswer) {
    var html = '';
    
    html += '<div class="question">';
    
    html += '<div class="rowElem nobg">';
    html += '<label>Câu hỏi</label>';
    html += '<div class="formRight">';
    html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bQuestion" name="textarea">' + question + '</textarea>';
    html += '<div class="floatright" onclick="removeQuestion(this);">';
    html += '<a class="btn14 mb5 floatright topDir" title="Xóa câu hỏi">';
    html += '<img src="/images/icons/dark/close.png" alt=""/>';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '<div class="fix"></div>';
    html += '</div>';

    html += '<div class="answerList">';

    for (var j = 0; j < listAnswer.length; j++) {    
        html += '<div class="rowElem">';
        html += '<label>Đáp án</label>';    
        html += '<div class="formRight">';
        html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bAnswer" name="textarea">' + listAnswer[j].Answer + '</textarea>';    
        html += '<div class="floatright">';
        html += '<a class="btn14 mb5 topDir" title="Thêm đáp án" onclick="createAnswer(this);">';
        html += '<img src="/images/icons/dark/add.png" alt="" />';
        html += '</a>';
        html += '<br/>';
        html += '<a class="btn14 mb5 topDir" title="Xóa đáp án" onclick="removeAnswer(this);">';
        html += '<img src="/images/icons/dark/close.png" alt=""/>';
        html += '</a>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
    }    
    
    html += '</div>';
    html += '<div class="curves"></div>';
    html += '</div>';
    
    return html;
}
//#endregion

/***************************************
= Create Question
-------------------------------------- */
//#region
function createQuestion() {
    var html = '';

    html += '<div class="bigsize-item">';
    html += '<div class="question">';
    html += '<div class="rowElem nobg">';
    html += '<label>Câu hỏi</label>';
    html += '<div class="formRight">';
    html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bQuestion" name="textarea"></textarea>';
    html += '<div class="floatright" onclick="removeQuestion(this);">';
    html += '<a class="btn14 mb5 floatright topDir" title="Xóa câu hỏi">';
    html += '<img src="/images/icons/dark/close.png" alt=""/>';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '<div class="fix"></div>';
    html += '</div>';

    html += '<div class="answerList">';
    html += '<div class="rowElem">';
    html += '<label>Đáp án</label>';
    html += '<div class="formRight">';
    html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bAnswer" name="textarea"></textarea>';
    html += '<div class="floatright">';
    html += '<a class="btn14 mb5 topDir" title="Thêm đáp án" onclick="createAnswer(this);">';
    html += '<img src="/images/icons/dark/add.png" alt="" />';
    html += '</a>';
    html += '<br/>';
    html += '<a class="btn14 mb5 topDir" title="Xóa đáp án" onclick="removeAnswer(this);">';
    html += '<img src="/images/icons/dark/close.png" alt=""/>';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '<div class="curves"></div>';
    html += '</div>';
    html += '</div>';

    $('.bigsize').append(html);

    delegateTooltip();
}
//#endregion
/***************************************
= Remove Question
-------------------------------------- */
//#region
function removeQuestion(obj) {
    $(obj).parents('.bigsize-item').fadeOut('slow', function () {
        $(this).remove();
    });                            
}
//#endregion

/***************************************
= Create Answer
-------------------------------------- */
//#region
function createAnswer(obj) {
    var html = '';    
    html += '<div class="rowElem">';
    html += '<label>Đáp án</label>';
    html += '<div class="formRight">';
    html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bAnswer" name="textarea"></textarea>';
    html += '<div class="floatright">';
    html += '<a class="btn14 mb5" onclick="createAnswer(this);">';
    html += '<img src="/images/icons/dark/add.png" alt="" class="floatright topDir" title="Thêm đáp án"/>';
    html += '</a>';
    html += '<br/>';
    html += '<a class="btn14 mb5" onclick="removeAnswer(this);">';
    html += '<img src="/images/icons/dark/close.png" alt="" class="floatright topDir" title="Xóa đáp án"/>';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';

    $(obj).parents('.answerList').append(html);
}
//#endregion
/***************************************
= Remove Answer
-------------------------------------- */
//#region
function removeAnswer(obj) {
    $(obj).parents('.rowElem').fadeOut('slow', function () {
        $(this).remove();
    });                    
}
//#endregion

//**************************************************************************************************************************************************************//
// PREVIEW
//**************************************************************************************************************************************************************//

/***************************************
= Preview (HeheHoro | Tarot | Horodaily, SingleSeat | CoupleSeat, WhoLoveMe | SmallSize, BigSize)
-------------------------------------- */
//#region
function preview(id, type) {
    $('#popup_container').css('display', 'block');

    $('#popup_title').empty();
    $('#popup_message').empty();

    switch (type) {
        case "QA":
            pQA(id);
            break;
        case "hehehoro":
            pHeheHoro(id);
            break;
        case "horodaily":
            pOneZodiac(id, "horodaily");
            break;
        case "singleseat":
            pOneZodiac(id, "singleseat");
        case "coupleseat":
            pTwoZodiac(id, "coupleseat");
            break;
        case "wholoveme":
            pTwoZodiac(id, "wholoveme");
            break;
        case "smallsize":
            pQuizzyShop(id, "smallsize");
            break;
        case "bigsize":
            pQuizzyShop(id, "bigsize");
            break;
        case "vipquiz":
            pVipQuiz(id);
            break;
        case "topquizzer":
            pTopQuizzer(id);
            break;
        case "comment":
            pComment(id);
            break;
    }
}

function pQA(id) {

    $.getJSON("/Handlers/PreviewHandler.ashx", { 'command': 'qa', 'id': id }, function (result) {
        $('#popup_title').append('Xem trước QA');

        var body = '';
        
        body += '<div class="preview_qa">';
        body += '<div>';
        body += '<p>' + result.QA_Text + '</p>';
        body += '</div>';
        body += '</div>';
        body += '<div class="fix"></div>';

        $.each(result.lstAnswer, function (index, value) {
            body += '<div class="list tipGreen pt12">';
            body += '<span class="legend"> Trả lời ' + (index + 1) + ':</span>';
            body += '<ul>';
            body += '<li>' + value.QA_Text + '</li>';
            body += '</ul>';
            body += '</div>';
        });
        body += '<div class="fix"></div>';
        body += '<strong>Ngày gửi: </strong> <span class="green" style="font-weight: bold">' + result.QA_CreatedDate + '</span>';

        $('#popup_message').append(body);
        $('#popup_message').css({ 'overflow-y': 'auto', 'height': '350px' });
    });
}

function pTarot(id) {
    $.getJSON("/Handlers/PreviewHandler.ashx", { 'command': 'tarot', 'id': id }, function (result) {
        $('#popup_title').append(result.Title);

        var body = '';        
        body += '<strong>Đầu tuần: </strong>' + result.Week + "<br/>";
        body += '<strong>Giữa tuần: </strong>' + result.MidWeek + "<br/>";
        body += '<strong>Cuối tuần: </strong>' + result.Weekend + "<br/>";
        body += '<strong>Ngày xuất bản: </strong> <span class="green" style="font-weight: bold">' + result.PublishOn + '</span>';
        $('#popup_message').append(body);
    });
}

function pHeheHoro(id) {
    $.getJSON("/Handlers/PreviewHandler.ashx", { 'command': 'hehehoro', 'id': id }, function (result) {
        $('#popup_title').append(result.Title);

        var body = '';
        body += '<strong>Tóm tắt: </strong>' + result.Sapo + "<br/>";

        if (result.ImgDetail != null) {
            if (result.ImgDetail.indexOf('http://') != -1) {
                body += '<img  style="width: 440px" src="' + result.ImgDetail + '" alt=""/><br/>';    
            }
            else {
                body += '<img  style="width: 440px" src="' + Base64.decode(Domain) + result.ImgDetail + '" alt=""/><br/>';    
            }
        }

        if (result.ImgZodiac == true)
            body += '<img  style="width: 440px; margin-top: 10px;" src="/images/chu-thich-cac-cung.jpg" alt=""/><br/>';

        body += '<strong>Ngày xuất bản: </strong> <span class="green" style="font-weight: bold">' + result.PublishOn + '</span>';
        $('#popup_message').append(body);
        $('#popup_message').css({ 'overflow-y': 'auto', 'height': '350px' });
    });
}

function pOneZodiac(id, name) {
    var typeId = 0;
    if (name == 'horodaily')
        typeId = 1;
    else if (name == 'singleseat')
        typeId = 2;

    $.getJSON("/Handlers/PreviewHandler.ashx", { 'command': name, 'id': id, 'typeId': typeId }, function (result) {
        $('#popup_title').append(result.Title);

        var body = '';

        body += '<div class="preview_smallsize">';
        body += '<div>';
        body += '<img src="' + originalImg(result.ImgAvatar) + '" alt="" width="130" height="98"/>';
        body += '<strong>Tiêu đề phụ: </strong>' + result.SubTitle + "<br/>";
        body += '<p><strong>Tóm tắt: </strong>' + result.Sapo + '</p>';
        body += '</div>';
        body += '</div>';
        body += '<div class="fix"></div>';

        if (result.OneZodiacContent.length > 0) {
            for (var i = 0; i < result.OneZodiacContent.length; i++) {
                $.ajax({
                    url: "/Handlers/PreviewHandler.ashx",
                    data: { 'command': 'getzodiacname', 'id': result.OneZodiacContent[i].ZodiacId },
                    type: 'get',
                    dataType: 'json',
                    async: false,
                    success: function (data) {
                        body += String.format('<strong class="green">{0}</strong>: {1}<br/><br/>', data, result.OneZodiacContent[i].Body);
                    }
                });
            }
        }

        body += '<strong>Ngày xuất bản: </strong> <span class="green" style="font-weight: bold">' + result.PublishOn + '</span>';
        $('#popup_message').append(body);
        $('#popup_message').css({ 'overflow-y': 'auto', 'height': '350px' });
    });
}

function pTwoZodiac(id, name) {
    var typeId = 0;
    if (name == 'coupleseat')
        typeId = 3;
    else if (name == 'wholoveme')
        typeId = 4;

    $.getJSON("/Handlers/PreviewHandler.ashx", { 'command': name, 'id': id, 'typeId': typeId }, function (result) {
        $('#popup_title').append(result.Zodiac1 + ' - ' + result.Zodiac2);

        var body = '';
        body += '<strong>Nội dung: </strong>' + result.Body + "<br/>";

        body += '<strong>Ngày xuất bản: </strong> <span class="green" style="font-weight: bold">' + result.PublishOn + '</span>';
        $('#popup_message').append(body);
    });
}

function pQuizzyShop(id, name) {
    var typeId = 0;
    if (name == 'smallsize')
        typeId = 5;
    else if (name == 'bigsize')
        typeId = 6;

    $.getJSON("/Handlers/PreviewHandler.ashx", { 'command': name, 'id': id, 'typeId': typeId }, function (result) {
        $('#popup_title').append(result.Title);

        var body = '';        

        // quizzy shop
        body += '<div class="preview_smallsize">';
        body += '<div>';
        body += '<img src="' + originalImg(result.ImgAvatar) + '" alt="" width="130" height="98"/>';
        body += '<p>' + result.Sapo + '</p>';
        body += '</div>';
        body += '</div>';
        body += '<div class="fix"></div>';

        if (name == 'smallsize') {
            $.each(result.SmallSize, function (index, value) {
                body += '<div class="list tipGreen pt12">';
                body += '<span class="legend">' + value.Title + '</span>';
                body += '<ul>';
                body += '<li>' + value.Result + '</li>';
                body += '</ul>';
                body += '</div>';
            });
        }
        else if (name == 'bigsize') {
            // question & answer

            for (var i = 0; i < result.QuizzyShopModel.length; i++) {
                body += '<div class="list tipGreen pt12">';
                body += '<span class="legend">' + result.QuizzyShopModel[i].ListQuestion[0].Question + '</span>';
                body += '<ul>';

                for (var j = 0; j < result.QuizzyShopModel[i].ListAnswer.length; j++) {
                    body += '<li>' + result.QuizzyShopModel[i].ListAnswer[j].Answer + '</li>';
                }

                body += '</ul>';
                body += '</div>';
            }

            // big size result
            body += '<div class="list tipGreen pt12">';
            body += '<span class="legend">Lời chiêm tinh</span>';
            body += '<ul>';
            $.each(result.BigSize, function (index, value) {
                body += '<li>' + value.Result + '</li>';
            });
            body += '</ul>';
            body += '</div>';
        }
        body += '<div class="fix"></div>';
        body += '<strong>Ngày xuất bản: </strong> <span class="green" style="font-weight: bold">' + result.PublishOn + '</span>';

        $('#popup_message').append(body);
        $('#popup_message').css({ 'overflow-y': 'auto', 'height': '350px' });
    });
}

function pVipQuiz(id) {
    $.getJSON("/Handlers/PreviewHandler.ashx", { 'command': 'vipquiz', 'id': id }, function (result) {
        $('#popup_title').append(result.Title);

        var body = '';
        body += '<strong>Nội dung: </strong>' + result.Body + "<br/>";
        
        body += '<strong>Ngày xuất bản: </strong> <span class="green" style="font-weight: bold">' + result.PublishOn + '</span>';
        $('#popup_message').append(body);
    });
}

function pTopQuizzer(id) {
    $.getJSON("/Handlers/PreviewHandler.ashx", { 'command': 'topquizzer', 'id': id }, function (result) {
        $('#popup_title').append(result.Title);

        var body = '';
        body += '<strong>Tóm tắt: </strong>' + result.Sapo + "<br/>";
        body += '<strong>Nội dung: </strong>' + result.Body + "<br/>";

        body += '<strong>Ngày xuất bản: </strong> <span class="green" style="font-weight: bold">' + result.PublishOn + '</span>';
        $('#popup_message').append(body);
        $('#popup_message').css({ 'overflow-y': 'auto', 'height': '350px' });
    });
}

function pComment(id) {
    $.getJSON("/Handlers/PreviewHandler.ashx", { 'command': 'comment', 'id': id }, function (result) {
        $('#popup_title').append(result.Title);

        var body = '';        
        body += '<strong>Nội dung: </strong>' + result.Body + "<br/>";

        body += '<strong>Thời gian: </strong> <span class="green" style="font-weight: bold">' + result.PublishOn + '</span>';
        $('#popup_message').append(body);        
    });
}

function closePreview() {
    $('#popup_container').hide();
}
//#endregion

/***************************************
= Preview Image
-------------------------------------- */

function quickViewImage(imgPath, width, height) {
    if (imgPath.length > 0) {
        $('#popup_container').css('display', 'block');
        $('#popup_title').empty();
        $('#popup_message').empty();

        $('#popup_title').append(imgPath);

        //$('#popup_panel').html('');
        $('#popup_message').removeAttr('style', '');

        if (imgPath.substring(0, 1) == '/')
            imgPath = imgPath.substring(1, imgPath.length);
        
        var body = '';
        body += String.format('<center><img src="{0}thumb/{1}_{2}/{3}" alt=""/></center>', Base64.decode(Domain), width, height, imgPath);
        console.log(body);

        $('#popup_message').append(body);
    }        
}

function thumbW(width, imgPath) {
    if (imgPath.substring(0, 1) == '/')
        imgPath = imgPath.substring(1, imgPath.length);
    return String.format('{0}thumb_w/{1}/{2}', Base64.decode(Domain), width, imgPath);
}

function thumb(width, height, imgPath) {
    if (imgPath.substring(0, 1) == '/')
        imgPath = imgPath.substring(1, imgPath.length);
    return String.format('{0}thumb/{1}_{2}/{3}', Base64.decode(Domain), width, height, imgPath);
}

function zoom(width, height, imgPath) {
    if (imgPath.substring(0, 1) == '/')
        imgPath = imgPath.substring(1, imgPath.length);
    return String.format('{0}zoom/{1}_{2}/{3}', Base64.decode(Domain), width, height, imgPath);
}

//#region
function viewImage(objName, imgType,  width, height) {
    var imgPath = $('#' + objName).val();
    if (imgPath.substring(0,1) == '/') 
        imgPath = imgPath.substring(1, imgPath.length);
    if (imgPath.length > 0) {
        $('#popup_container').css('display', 'block');
        $('#popup_title').empty();
        $('#popup_message').empty();

        $('#popup_title').append(imgPath);

        //$('#popup_panel').html('');
        $('#popup_message').removeAttr('style', '');

        var body = '';
        switch (imgType) {
            case 'orginal':
                body += String.format('<center><img src="{0}/{1}" alt=""/></center>', Base64.decode(Domain), imgPath);                
                break;
        
            case 'detail':
                body += String.format('<br><img src="{0}" alt="" style="width: 440px;"/><br>', thumbW(700, imgPath));
                $('#popup_message').css({ 'overflow-y': 'auto', 'height': '350px' });
                //$('#popup_panel').append('<input type="button" value="&nbsp;Đóng&nbsp;" onclick="closePreview();" class="blueBtn floatright"/>');                
                break;

            default:
                body += String.format('<center><img src="{0}thumb/{1}_{2}/{3}" alt=""/></center>', Base64.decode(Domain), width, height, imgPath);
                console.log("ViewImage Default: " + body);
                break;
        }
                                        
        $('#popup_message').append(body);        
    }

    /*
    var imagePath = '';
    
    switch (type) {
        case "img":
            $('#viewImage').empty();
            var imagePath = $('#txtImage').val();            
            break;
        case "img-zodiac":
            $('#viewImage').empty();
            var imagePath = $('#txtImageDescription').val();
            break;            
    }
        
    if (imagePath != null && imagePath.length > 0) {
        $('#viewImage').append('<img src=' + imagePath + ' style="width: 300px" alt=""/>');
        $('#viewImage').show();
    }
    */
}

function closeViewImage() {
    //$('#viewImage').hide();
    $('#popup_container').hide();
}
//#endregion


/***************************************
= Base64
-------------------------------------- */
var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode: function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}

/***************************************
= Remove Sign
-------------------------------------- */

//#region
function removeSign(str) {
    str = str.toLowerCase();
    str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a");
    str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
    str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
    str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o");
    str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
    str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
    str = str.replace(/đ/g, "d");
    str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g, "-");

    /* tìm và thay thế các kí tự đặc biệt trong chuỗi sang kí tự - */
    str = str.replace(/-+-/g, "-"); //thay thế 2- thành 1-     
    str = str.replace(/^\-+|\-+$/g, "");

    //cắt bỏ ký tự - ở đầu và cuối chuỗi  
    return str;
}
//#endregion

/***************************************
= Cleat cache facebook
-------------------------------------- */
var fb_host = "http://quizz.kenh14.vn/";
//var fb_host = "http://b12.channelvn.net/";
//var fb_host = "http://localhost:6868/";
var fb_time = 0;
var fb_count = 0;
var SINGLESEATTYPE = "single-seat";
var HORODAILYTYPE = "horo-daily";

function fb_clearCache() {
//    var c = confirm('Nạp cache facebook nhiều lần dễ bị bên facebook hiểu nhầm là spam, bạn chỉ nên nạp lại 1 lần mỗi ngày!');
//    if (c) {
        $.getJSON("/Handlers/EventHandler.ashx", { 'command': 'zodiacgetall' }, function (result) {
            if (result != null) {
                fb_time = 0;
                fb_count = 0;
                var link;
                var i;
                for (i = 0; i < 12; i++) {
                    link = fb_oneZodiacBuildLink(HORODAILYTYPE, result[i].ZodiacId, result[i].Name);
                    fb_timeout(link);
                }
                for (i = 0; i < 12; i++) {
                    link = fb_oneZodiacBuildLink(SINGLESEATTYPE, result[i].ZodiacId, result[i].Name);
                    fb_timeout(link);
                }
                for (i = 0; i < 12; i++) {
                    for (var j = 0; j < 12; j++) {
                        link = fb_twoZodiacBuildLink('couple-seat', result[i].ZodiacId, result[j].ZodiacId, result[i].Name, result[j].Name);
                        fb_timeout(link);
                    }
                }
            }
        });
//    } else return false;
}

function fb_timeout(link) {
    setTimeout(function () {
        fb_excRequest(link);
    }, fb_time * 5000);
    fb_time++;
}

function fb_excRequest(link) {
    $.ajax({
        url: "http://developers.facebook.com/tools/debug/og/echo?q=" + encodeURI(link) + "&callback=?",
        type: 'GET',
        async: false,
        dataType: 'jsonp'
    });
    fb_count++;
    $('#fb_log').append("[" + fb_count + "/168] " + link + "<br>");
    switch (fb_count) {
        case 12:
            $('#fb_log').append(" - Đã nạp xong cache facebook của horo daily<br>");
            break;
        case 24:
            $('#fb_log').append(" - Đã nạp xong cache facebook của single seat<br>");
            break;
        case 168:
            $('#fb_log').append(" - Đã nạp xong cache facebook của coulple seat<br>");
            $('#fb_log').append(" - Đã hoàn thành tiến trình!<br>");
            break;
    }    
}

function fb_oneZodiacBuildLink(type, zodiacId, name)
{
    return String.format('{0}s/{1}/{2}/{3}-{4}.htm', fb_host, type, zodiacId, getShortDateNow2(), removeSign(name));
}

function fb_twoZodiacBuildLink(type, zodiacId1, zodiacId2, name1, name2) {
    return String.format('{0}s/{1}/{2}/{3}/{4}-{5}-{6}.htm', fb_host, type, zodiacId1, zodiacId2, getShortDateNow2(), removeSign(name1), removeSign(name2));
}

function getShortDateNow2() {
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    return String.format("{0}-{1}-{2}", day, month, year);
}

/***************************************
= tag autocomplete
-------------------------------------- */

function addTag(func) {
    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'taggetall' },
        type: 'GET',
        dataType: "json",
        success: function (result) {
            if (typeof (func) == 'function') {
                func(result, tagModule);
            }
        }
    });
}

function currentTagDetails(list, func) {
    var id = $('#hfId').val();
    var typeId = $('#hfTypeId').val();
    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'taggetbyid', 'id': id, 'typeId': typeId },
        type: 'GET',
        dataType: "json",
        success: function (result) {
            if (typeof (func) == 'function') {
                func(list, result);
            }
        }
    });
}

function dynamicCurrentTagDetails(list, func) {
    var current = $('#tag-autocomplete').tokenInput("get");
    if (typeof (func) == 'function') {
        func(list, current);
    }
}

function tagModule(list, current) {
    $("#tag-autocomplete").tokenInput(list, {
        theme: "facebook",
        prePopulate: current
    });
}

function getTag() {
    var lst = $("#tag-autocomplete").val();
    $('#hfTag').val(lst);
}


function checkTagValid() {
    var tag = $('.txtAddTag').val();
    tag = ($).trim(tag);
    if (tag == null || tag == '') return;
    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'checktagvalid', 'tag': tag },
        type: 'GET',
        dataType: "json",
        success: function (result) {
            if (result != null) {
                if (result > 0) alert("Tag đã tồn tại!");
                else {
                    addDynamicTag(tag);
                    $('.txtAddTag').val("");
                }
            }
        }
    });
}

function addDynamicTag(tag) {
    var username = $('#hfUsername').val();
    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'addtag', 'tag': tag, 'username': username },
        type: 'GET',
        dataType: "json",
        success: function (result) {
            if (result != null) {
                $("#tag-contain .token-input-list-facebook").remove();
                addTag(dynamicCurrentTagDetails);
            }
        }
    });
}

/***************************************
= company autocomplete
-------------------------------------- */

function addCompany(func) {
    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'companygetall' },
        type: 'GET',
        dataType: "json",
        success: function (result) {
            if (typeof (func) == 'function') {
                func(result, companyModule);
            }
        }
    });
}

function currentCompanyDetails(list, func) {
    var id = $('#hfCompany').val();
    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'companygetbyid', 'id': id },
        type: 'GET',
        dataType: "json",
        success: function (result) {
            if (typeof (func) == 'function') {
                func(list, result);
            }
        }
    });
}

function dynamicCurrentCompanyDetails(list, func) {
    var current = $('#company-autocomplete').tokenInput("get");
    if (typeof (func) == 'function') {
        func(list, current);
    }
}

function companyModule(list, current) {
    $("#company-autocomplete").tokenInput(list, {
        theme: "facebook",
        prePopulate: current
    });
}

function getCompany() {
    var lst = $("#company-autocomplete").val();
    if (lst == '' || lst.length == 0) lst = 0;
    $('#hfCompany').val(lst);
}

//**************************************************************************************************************************************************************//
// QA
//**************************************************************************************************************************************************************//

/***************************************
= Create QA
-------------------------------------- */
//#region
function createQABlank() {
    var html = '';
    html += '<div class="qa-item">';
    html += '<div class="mt10">';
    html += '<a class="btn14 mr17 floatright topDir" onclick="removeQA(this);" title="Xóa câu trả lời"><img src="/images/icons/dark/close.png" alt="" /></a>';
    html += '</div>';
    html += '<div class="fix"></div>';
    html += '<div class="rowElem nobg">';
    html += '<label>Câu trả lời</label>';
    html += '<div class="formRight"><textarea name="textarea" class="validate[required] sResult" cols="" rows="5"></textarea></div>';
    html += '<div class="fix"></div>';
    html += '</div>';
    html += '<div class="curves"></div>';
    html += '</div>';

    $('.qa-answer').append(html);
}
//#endregion

//#region
function createQA(result) {
    var html = '';
    html += '<div class="qa-item">';
    html += '<div class="mt10">';
    html += '<a class="btn14 mr17 floatright topDir" onclick="removeQA(this);" title="Xóa câu trả lời"><img src="/images/icons/dark/close.png" alt="" /></a>';
    html += '</div>';
    html += '<div class="fix"></div>';

    html += '<div class="rowElem nobg">';
    html += '<label>Câu trả lời</label>';
    html += '<div class="formRight"><textarea name="textarea" class="validate[required] sResult" cols="" rows="5">' + result + '</textarea></div>';
    html += '<div class="fix"></div>';
    html += '</div>';
    html += '<div class="curves"></div>';
    html += '</div>';

    return html;
}
//#endregion

/***************************************
= Remove QA
-------------------------------------- */
//#region
function removeQA(obj) {
    $(obj).parents('.qa-item').fadeOut('slow', function () {
        $(this).remove();
    });
}
//#endregion

/***************************************
= Get Data QA
-------------------------------------- */
//#region
function getDataQA() {
    var contentList = '';
    $('.qa-item').each(function () {
        contentList += $(this).find('.sResult').val() + '►';
    });
    // set list result to textbox
    $('#txtContentList').val(contentList);
}
//#endregion

/***************************************
= Bind Data QA
-------------------------------------- */
//#region
function binDataQA(id) {
    var lst = '';
    $.getJSON("/Handlers/EventHandler.ashx", { 'command': 'bindqabyreplyto', 'id': id }, function (result) {
        for (var i = 0; i < result.length; i++) {
            lst += createQA(result[i].QA_Text);
        }
        $('.qa-answer').html(lst);
    });
}
//#endregion



/***************************************
= popup compny lien quan
-------------------------------------- */
//#region
function openListCompany(data) {
    var w = window.open('/PopupListCompany.aspx?id=' + data, 'Chọn các công ty trùng lặp', 'status = 1, scrollbars = 1, height = 470, width = 810');
    w.focus();
    return false;
}
//#endregion

//#region  
// Callback Function Of popup tin lien quan
function setTargetFieldCompany(value) {
    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'getlistrelation', 'relation': value},
        type: 'GET',
        dataType: "json",
        success: function (result) {
            if (result != null) {
                for (var i = 0; i < result.length; i++) {
                    $('#sbRelation').append('<option value="' + result[i].id + '">' + result[i].name + '</option>');
                }
            }
        }
    });
    window.focus();
}
//#endregion

//#region  
// xoa item trong list bai lien quan
function removeCompanyItem() {
    $('#sbRelation option:selected').each(function () {
        $(this).remove();
    });
}
//#endregion

//#region  
// chuyen len xuong phan tu trong list item
function moveUpItem() {
    $('#sbRelation option:selected').each(function () {
        $(this).insertBefore($(this).prev());
    });
}

function moveDownItem() {

    $('#sbRelation option:selected').each(function () {
        $(this).insertAfter($(this).next());
    });

}
//#endregion

//#region  
// day list id bai lien quan vao hf den chuyen ve phia server
function getRelation() {
    var relation = '';
    $('#sbRelation option').each(function () {
        if (relation == '') relation = $(this).val();
        else relation += ',' + $(this).val();
    });
    $('#hfRelation').val(relation);
}
//#endregion

/***************************************
= bind member album
-------------------------------------- */
function bindMemberAlbum(control, id, round) {
    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'memberalbumbyid', 'id': id, 'round': round },
        type: 'GET',
        dataType: "json",
        async: false,
        success: function (result) {
            if (result != null) {
                var format = '<img style="margin: 1px" alt="" src="{0}" />';
                var html = '';
                for (var i = 0; i < result.length; i++) {
                    html += String.format(format, zoom(50, 50, result[i].Photo_Url));

                }
                control.html(html);                
            }
        }
    });
}

/***************************************
= toggle status
-------------------------------------- */
function memberToggleIsHomePage(control) {
    var $control = $(control);
    var id = $control.attr('mid');

    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'memberupdateishomepage', 'id': id },
        type: 'GET',
        dataType: "json",
        async: true,
        success: function () {
            
            var src = $control.attr('ishomepage') == "True" ? "/images/icons/color/user-black-female.png" : "/images/icons/color/pin.png";
            var ishomepage = $control.attr('ishomepage') == "True" ? "False" : "True";
            var title = $control.attr('ishomepage') == "True" ? "Bình thường" : "Nổi bật trang chủ";
            $control.attr('src', src);
            $control.attr('ishomepage', ishomepage);
            $control.attr('title', title);
        }
    });
}

function memberToggleIsSlide(control) {
    var $control = $(control);
    var id = $control.attr('mid');

    $.ajax({
        url: '/Handlers/EventHandler.ashx',
        data: { 'command': 'memberupdateisslide', 'id': id },
        type: 'GET',
        dataType: "json",
        async: true,
        success: function () {

            var src = $control.attr('isslide') == "True" ? "/images/icons/color/user-black-female.png" : "/images/icons/color/pin.png";
            var isslide = $control.attr('isslide') == "True" ? "False" : "True";
            var title = $control.attr('isslide') == "True" ? "Bình thường" : "Hiển thị trên slide";
            $control.attr('src', src);
            $control.attr('isslide', isslide);
            $control.attr('title', title);
        }
    });
}